<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
 

class b2c_syncerp
{
    /**
     * ERP从Ecstore获取商品
     */
    public function getGoods()
    {
        $obj_goods = app::get('b2c')->model('goods');
		//$params = array_merge($params,array_merge($_GET,$_POST));
		$params = array_merge($_GET,$_POST);
		//过滤条件
		$page_size = $params['page_size'] ? $params['page_size'] : 50;

		//商品ID
		if($params['goods_id'])
		{
			$params_goods_ids = explode(',',$params['goods_id']);
			$filter['goods_id|in'] = $params_goods_ids;
		}
		
		//商品编号
		if($params['bn'])
		{
			$bns = explode(',',$params['bn']);
			$filter['bn|in'] = $bns;
		}

		//货号
		if($params['ibn'])
		{
			$bns = explode(',',$params['ibn']);
			$obj_products = app::get('b2c')->model('products');
			$product_datas = $obj_products->getList('goods_id',array('bn|in'=>$bns));
			$goods_ids = array();
			foreach($product_datas as $p)
			{
				$goods_ids[] = $p['goods_id'];
			}
			if(empty($goods_ids))
			{
				$goods_ids[] = '-1';
			}
			$filter['goods_id|in'] = $goods_ids;
		}

		if($params['from_time'] || $params['to_time'])
		{
			$filter_sql = array();
			if($params['from_time'])
			{
				$filter_sql[] = ' last_modify >='.strtotime($params['from_time']);
			}
			if($params['to_time'])
			{
				$filter_sql[] = ' last_modify <='.strtotime($params['to_time']);
			}
			$filter['filter_sql'] = implode(' and ',$filter_sql);
		}

		if(empty($params))
		{
			$filter['sync_flag'] = 'false';
			$page_no = 1;
		}
		else
		{
			$page_no = $params['page_no'] ? $params['page_no'] : 1;
		}
		//获取最大页数
		$count = $obj_goods->count($filter);
        $maxPage = ceil($count / $page_size);

		//获取商品数据
		$start = ($page_no-1) * $page_size;
        $start = $start < 0 ? 0 : $start;

        if($page_no > $maxPage)
		{
			$result = array('data'=>array('goods'=>array(),'total'=>0));
		}
		else
		{
			$goods = $obj_goods->getList('*',$filter,$start,$page_size);
			$res_goods = array();
			$obj_brand = app::get('b2c')->model('brand');
			$obj_business = app::get('b2c')->model('business_basicmsg');
			$obj_goodstype = app::get('b2c')->model('goods_type');
			$obj_products = app::get('b2c')->model('products');
			$goods_ids = array();
			foreach($goods as $g)
			{
				$gtype = $obj_goodstype->getRow("name",array('type_id'=>$g['type_id']));
				$product = $obj_products->getRow("bn",array('goods_id'=>$g['goods_id']));
				$temp_g = array(
					'goods_id' => $g['goods_id'],				//ID
					'bn'       => $g['bn'],						//商品编号
					'ibn'      => $product['bn'],               //商品货号
					'name'     => $g['name'],					//商品名称
					'unit_num' => $g['unit_num'],				//每包装数量
					'unit'     => $g['unit'],					//销售单位
					'bag_unit' => $g['bag_unit'],				//包装单位
					's_price'  => $g['s_price'],				//销售单价
					'cost'	   => $g['cost'],					//采购结算价
					'business_name'=> $obj_business->get_english_name($g['business_id']),		//供应商名称
					'business_id'  => $g['business_id'],		//供应商ID
					'brand'    => $obj_brand->get_brand_name($g['brand_id']),					//品牌
					'type'     => $gtype['name'],				//商品类型
					'weight'   => $g['weight'],					//重量
					'capacity' => $g['capacity'],				//体积
				);
				$res_goods[] = $temp_g;
				$goods_ids[] = $g['goods_id'];
			}
			$obj_goods->update(array('sync_flag'=>'true'),array('goods_id'=>$goods_ids),array('sync_flag'=>'true'));
			
			$result = array('data'=>array('goods'=>$res_goods,'total'=>count($res_goods)),'page'=>array('page_no'=>$page_no,'page_total'=>$maxPage));
		}
        echo json_encode($result);exit;
    }
    
    /**
     * 订单确认库存并确认运费后（待付款状态）
     */
    public function getConfirmedOrders(){
		//$params = array_merge($params,array_merge($_GET,$_POST));
		$params = array_merge($_GET,$_POST);
		$result = $this->getOrders($params);
        echo json_encode($result);
    }

	//集货后 状态：集货完成
	public function getCollectedOrders(){
		$params = array_merge($_GET,$_POST);
		$result = $this->getOrders($params,'1');
        echo json_encode($result);
    }

	function getOrders($params,$flag=null)
	{
		$ordersMdl = app::get('b2c')->model('orders');
        $filter = $this->getFilter($params,$flag);
		if(empty($params))
		{
			$filter['sync_flag'] = 'false';
			$page_no = 1;
		}
		else
		{
			$page_no = $params['page_no'] ? $params['page_no'] : 1;
		}

		//过滤条件
		$page_size = $params['page_size'] ? $params['page_size'] : 50;

		//获取最大页数
		$count = $ordersMdl->count($filter);

        $maxPage = ceil($count / $page_size);

		
		$start = ($page_no-1) * $page_size;
        $start = $start < 0 ? 0 : $start;

        if($page_no > $maxPage)
		{
			$result = array('data'=>array('orders'=>null,'total'=>0),'page'=>array('page_no'=>$page_no,'page_total'=>$maxPage));
		}
		else
		{
			$orders = $ordersMdl->getList('*',$filter,$start,$page_size);
			$order_datas = array();
			$order_ids = array();
			foreach($orders as $key => $order){
				$res = $this->get_order_info($order,$flag);
				$order_datas[$key] = $res;
				$order_ids[] = $res['order']['order_id'];
			}
			//更新已读状态
			$ordersMdl->update(array('sync_flag'=>'true'),array('order_id'=>$order_ids));
			$result = array('data'=>array('orders'=>$order_datas,'total'=>count($orders)),'page'=>array('page_no'=>$page_no,'page_total'=>$maxPage));
		}
		return $result;
	}

	public function getOrderPayStatus(){

		$redis = kernel::single('base_kvstore_redis2');
		$tmp = '11order:'.microtime(1);
		$redis->set($tmp,json_encode($_REQUEST));
		die;
		$data = $_REQUEST;
		$status = 'A0001';
		$host = 'www.qifa.ru';

		$sign = md5(md5($host).md5($data['order_id']).md5($data['order_amount']).md5($data['pay_status']));
		if($sign == $data['sign']){
			$ordersModel =app::get('b2c')->model('orders');
			$orders = $ordersModel->getRow('*',array('order_id'=>$data['order_id']));
			if(!$orders){
				$msg = 'order:订单不存在';
			}
			else
			{
				if($data['pay_status'] == 'pay_success'){//返回支付成功
					$odata['pay_status'] = '1';//已支付
					$odata['order_id'] = $data['order_id'];

					if($ordersModel->save($odata)){
						$status = 'A0006';
						$msg	= '';

					}
				}elseif($data['pay_status'] == 'pay_failure'){//返回支付失败
					$status = 'A0001';
					$msg = 'pay:订单支付失败';
				}
			}


		}else{
			$msg   ='sign ：来源验证错误';
		}


		$result['status'] = $status;
		$result['msg']	= $msg;
		return $result;

	}

    //获取订单过滤条件 by yyj 2015/12/14
    private function getFilter($params,$flag=null){
		if($flag)
		{
			$filter = array(
				'status'=>'active',
				'c_status'=>'3'
			);
		}
		else
		{
			$pay_status = array('0','1','2','3');
			$filter = array(
                'status|in'=>array('active','dead'),
				'c_status'=>'2',
				'pay_status|in'=>$pay_status,
			);
		}
        if($params['order_id'] && !empty($params['order_id'])){
			$order_ids = explode(',',$params['order_id']);
			$filter['order_id|in'] = $order_ids;
        }
		//-----liuyulei确认时间过滤----
		if($params['confirm_time'] && !empty($params['confirm_time'])){
			$confirm_time = strtotime(date('d-m-Y', strtotime($params['confirm_time'])));
			$confirm_time_end = $confirm_time + 24*60*60;
			$filter_sql[] = ' confirm_time >='.$confirm_time;
			$filter_sql[] = ' confirm_time <'.$confirm_time_end;
			$filter_sql = '('.implode(' and ',$filter_sql).')';
			//$filter_sql.= ' or  (createtime >='.$confirm_time.' and createtime <'.$confirm_time_end.') ';
			$filter['filter_sql']  = $filter_sql;
		}
		//-----liuyulei确认时间过滤 end----
		if($params['from_time'] || $params['to_time'])
		{
			$filter_sql = array();
			if($params['from_time'])
			{
				$filter_sql[] = ' createtime >='.strtotime($params['from_time']);
			}
			if($params['to_time'])
			{
				$filter_sql[] = ' createtime <='.strtotime($params['to_time']);
			}
			if($filter['filter_sql']) {
				$filter['filter_sql'] = implode(' and ', $filter_sql).' and '.$filter['filter_sql'];
			}else{
				$filter['filter_sql'] = implode(' and ', $filter_sql);
			}
		}
		if($params['from_confirmed_time'] || $params['to_confirmed_time'])
		{
			$filter_sql = array();
			if($params['from_confirmed_time'])
			{
				$filter_sql[] = ' confirm_time >='.strtotime($params['from_confirmed_time']);
			}
			if($params['to_confirmed_time'])
			{
				$filter_sql[] = ' confirm_time <'.strtotime($params['to_confirmed_time']);
			}
			if($filter['filter_sql']) {
				$filter['filter_sql'] = implode(' and ', $filter_sql).' and '.$filter['filter_sql'];
			}else{
				$filter['filter_sql'] = implode(' and ', $filter_sql);
			}
		}
		return $filter;
    }

    private function get_order_info($row,$flag=null){
        $login_name = kernel::single('b2c_user_object')->get_member_name(null,$row['member_id']);
        $order['order'] = array(
            'order_id'=>$row['order_id'],//
            'createtime'=>date('d-m-Y H:i:s',$row['createtime']),
            'login_name'=>$login_name,
            'payment'=>$row['payment'],
            'shipping'=>$row['shipping'],
            'styke'=>$row['styke'],
			'memo'=>$row['memo'],
            'final_amount'=>$row['final_amount'],
            'discount'=>$row['discount'],
			'cost_item'=>$row['cost_item'],//liuyulei 添加订单总金额
			'pmt_order'=>$row['pmt_order'],//liuyulei 添加优惠抵扣金额
			'pre_order'=>$row['pre_order'],//mll 添加订单是否预售标识
			'status'=>$row['status']=='active'?'Действителен':'Отменен',//liuyulei 添加订单状态
			'confirm_time'=>$row['confirm_time']?date('d-m-Y H:i:s',$row['confirm_time']):'',//liuyulei 确认时间
        );
		//如果是预售订单，加上预售订单号
		if($order['order']['pre_order']==='true'){
			$order['order']['pre_number'] = PRE_SALE.$row['pre_number'];
		}else{
			$order['order']['pre_number'] = '';
		}

		//-------------liuyulei 促销活动---------------
		//$row['order_id'] = '1601110';
		$get_order_use_pmt = $this->get_order_use_pmt($row['order_id']);
		$order['order']['order_pmt'] = $get_order_use_pmt['order_pmt'];
		$order['order']['pmt_goods'] = $get_order_use_pmt['pmt_goods'];
		$order['order']['score_u'] = $get_order_use_pmt['score_u'];
		//买家信息
		$order['member'] = $this->get_order_user($row['member_id']);
		//-------------liuyulei 促销活动 end---------------

        //商品明细
        $order['order_items'] = $this->get_order_items_info($row['order_id'],$flag,&$order_type);
		$order['order_type'] = $order_type;
		//liuyulei 获取商品的确认数量，为0则加备注
		$order_remark = '';
		foreach($order['order_items'] as $_oitem){
			if($_oitem['has_confirm_num']==0) {
				$order_remark.= $_oitem['bn'].':'.$_oitem['quantity'].':Нет в наличии;';
			}
		}
		if($order_remark) {
			$order['order']['remark'] = $order_remark;
		}
		//添加订单最早和最晚到货日期
		if($order['order_items']['temp'] && $order['order']['pre_order']==='true'){
			$order['order']['first_time'] = date('d-m-Y',min($order['order_items']['temp']));
			$order['order']['last_time'] = date('d-m-Y',max($order['order_items']['temp']));
			unset($order['order_items']['temp']);
		}else{
			$order['order']['first_time'] = '';
			$order['order']['last_time'] = '';
		}
		if(!$flag)
		{
			//付款单位
			$order['payment_unit'] = $this->get_payment_unit_info($row['company_id']);
			//收货地址
			$order['ship_addr'] = $this->get_ship_addr_info($row['addr_id']);
			//收货人
			$order['ship_preson'] = $this->get_ship_preson_info($row['consignee_id']);
		}
        return $order;
    }
    //-------------liuyulei 促销活动---------------
	private function get_order_use_pmt($order_id,$flag=null){
		//$subsdf = array('order_pmt'=>array('*'),'order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))) );
		$subsdf = array('order_pmt'=>array('*'));
		$order = app::get('b2c')->model('orders');
		$aOrder = $order->dump($order_id, '*', $subsdf);
		$data = array();
		if(isset($aOrder['order_pmt']) && count($aOrder['order_pmt'])>0){
			foreach($aOrder['order_pmt'] as $_val){
				$order_pmt[]= $_val['pmt_type'].':'.$_val['pmt_memo'];
			}
		}
		$data['order_pmt'] = empty($order_pmt)?'':implode(',',$order_pmt);
		$data['pmt_goods'] = $aOrder['pmt_goods'];
		$data['score_u'] = $aOrder['score_u'];

		return $data;
	}
	// liuyulei 买家信息
	private function get_order_user($member_id,$flag=null){
		$model_member = app::get('b2c')->model('members');
		$member = $model_member->dump($member_id, '*', array('pam_account'=>'*'));

		$data = array();
		if(isset($member) && count($member)>0){
			$data['login_account']= $member['pam_account']['local']['login_account'];
			$data['name']= $member['name'];
			$data['mobile']= $member['pam_account']['mobile']['phone_setting'].' '.$member['pam_account']['mobile']['login_account'];
			$data['area']= $member['contact']['area'];
			$data['email']= $member['pam_account']['email']['login_account'];
			$data['company_name']= $member['company_name'];
			$data['company_inn']= $member['company_inn'];
			switch($member['c_type']){
				case 0:$c_type = app::get('b2c')->_('ООО');break;
				case 1:$c_type = app::get('b2c')->_('ЗАО');break;
				case 2:$c_type = app::get('b2c')->_('ИП');break;
				case 3:$c_type = app::get('b2c')->_('个人');break;
			}
			$data['c_type']= $c_type;
		}
		return $data;
	}

    //商品明细 by yyj 2015/12/14
    private function get_order_items_info($order_id,$flag=null,&$order_type){
        $orderItemsMdl = app::get('b2c')->model('order_items');
        $goodsMdl = app::get('b2c')->model('goods');
        $brandMdl = app::get('b2c')->model('brand');
		$obj_business = app::get('b2c')->model('business_basicmsg');
        $productsMdl = app::get('b2c')->model('products');
        $orderItems = $orderItemsMdl->getList('*',array('order_id'=>$order_id));
		$business_orderMdl = app::get('b2c')->model('business_orders_objects');
        $items = array();
		$order_type_status = 0;
        foreach($orderItems as $key => $item){
            $goods = $goodsMdl->getRow('*',array('goods_id'=>$item['goods_id']));
			if($goods['business_id']=='349'){
				$order_type_status+=1;
			}
            $brand = $brandMdl->getRow('*',array('brand_id'=>$goods['brand_id']));
            $product = $productsMdl->getRow('*',array('product_id'=>$item['product_id']));
			$b_order_goods = $business_orderMdl->getRow('*',array('product_id'=>$item['product_id'],'mainOrder_id'=>$item['order_id']));
            //$account = $item['price']*(1-$brand['rebate']/100);
			//----liuyulei修改采购价不做任何计算-----
			$account = $item['cost'];
			//一双的价格
			$one_price = round($b_order_goods['order_refund']/$b_order_goods['quantity']);
			//差异数量=下单商品数量-已确认数量
			$diffent_num = intval($b_order_goods['quantity'])-$b_order_goods['has_confirm_num'];

			$items[$key] = array(
					'goods_id'=>$item['goods_id'],
					'bn'=>$goods['bn'],
					'ibn'=>$product['bn'],
					'business_name'=> $obj_business->get_english_name($goods['business_id']),		//供应商名称
					'business_id'  => $goods['business_id'],		//供应商ID
					'nums'=>$item['nums'],
					'unit_num'=>$goods['unit_num'],
					'price'=>$item['price'],
					'cost'=>$account,
					'g_price'=>$item['g_price'],
					'goods_price'=>$item['goods_price'],
					'package_price'=>$b_order_goods['order_refund'],
					'one_price'=>$one_price,
					'quantity'=>$b_order_goods['quantity'],
					'has_confirm_num'=>$b_order_goods['has_confirm_num'],
					'diffent_num'=>$diffent_num
            );
			//判断是否是预售商品，如果是添加商品到货日期和商品批次号
			if($goods['pre_sale']==='true'){
				$items[$key]['arrival_time'] = date('d-m-Y',$goods['arrival_time']);//商品到货时间
				$items[$key]['batch'] = $goods['batch']; //批次号
				$items['temp'][] = $goods['arrival_time'];//为获取订单最早最晚到货日期用，用完会销毁
			}else{
				$items[$key]['arrival_time']='';
				$items[$key]['batch']='';
			}
        }
		$order_type = $order_type_status>0?'qifa3':'qifa2';
        return $items;
    }

    //付款单位 by yyj 2015/12/14
    private function get_payment_unit_info($company_id){
        $companyMdl = app::get('b2c')->model('member_company');
        $company = $companyMdl->getRow('*',array('company_id'=>$company_id));
        $payment = array(
            'company_id'=>$company_id,
            'name'=>$company['name'],
            'type'=>$company['c_type'],
            'inn'=>$company['inn'],
            'email'=>'',
            'tel'=>$company['tel']?$company['phone_setting'].' '.$company['tel']:'',
            );
        return $payment;
    }

    //收货地址 by yyj 2015/12/14
    private function get_ship_addr_info($addr_id){
        $addrsMdl = app::get('b2c')->model('member_addrs');
        $row = $addrsMdl->getRow('*',array('addr_id'=>$addr_id));
		$address_area = explode(':',$row['area']);
        $addr = array(
            'id'=>$addr_id,
            'area'=>$address_area[1]?$address_area[1]:'',
            'addr'=>$row['addr'],
        );
        return $addr;
    }

    //收货人 by yyj 2015/12/14
    private function get_ship_preson_info($consignee_id){
        $consigneeMdl = app::get('b2c')->model('member_consignee');
        $row = $consigneeMdl->getRow('*',array('consignee_id'=>$consignee_id));
        $consignee = array(
            'id'=>$consignee_id,
            'name'=>$row['name'],
            'mobile'=>$row['mobile']?$row['phone_setting'].' '.$row['mobile']:''
        );
        return $consignee;
    }

	//依据email，修改c_type字段 2017/09/08 jyy
	public function getEmailModifyCtype()
	{
		//$params = json_decode(file_get_contents('php://input'),true);
		$params = array_merge($_GET,$_POST);//获取erp获取的email和c_type
		//$params['email'] = 'tanrui@mail.ru';
		//$params['c_type'] = 0;
		$membersModel = app::get('b2c')->model('members');
		$pamModel = app::get('pam')->model('members');
		if(!empty($params))
		{
			$pam_members = $pamModel->getRow('member_id,login_account',array('login_account'=>trim($params['email'])));
			if(!empty($pam_members)){
				$membersModel->update(array('c_type'=>$params['c_type']), array('member_id'=>$pam_members['member_id']));
				$msg = array('status'=> 'success');
				echo json_encode($msg);
			}else{
				$msg = array('status'=> 'email is not exist!');
				echo json_encode($msg);
			}
		}else{
			$msg = array('status'=>'error');
			echo json_encode($msg);exit();
		}
	}
}